package com.hqbzl.c1.rlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class Test3 {
    static final ReentrantLock ROOM = new ReentrantLock();
    static final Condition waitEat = ROOM.newCondition();
    static final Condition waitCigarette = ROOM.newCondition();

    static boolean hasEat = false;
    static boolean hasCigarette = false;

    public static void main(String[] args) {
        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("有烟没: {}", hasCigarette);
                while (!hasCigarette) {
                    try {
                        log.debug("等烟来");
                        waitCigarette.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (hasCigarette) {
                    log.debug("有烟了，开始干活");
                } else {
                    log.debug("没烟不干活");
                }
            } finally {
                ROOM.unlock();
            }
        }, "小南").start();
        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("外卖到没有：{}", hasEat);
                while (!hasEat) {
                    try {
                        log.debug("等外卖到");
                        waitEat.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (hasEat) {
                    log.debug("外卖到了，可以开吃了");
                } else {
                    log.debug("外卖没到，不干活");
                }
            } finally {

            }
        }, "小女").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("我准备送烟了");
                hasCigarette = true;
                waitCigarette.signal();
            } finally {
                ROOM.unlock();
            }
        }, "送烟线程").start();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("外卖送到了");
                hasEat = true;
                waitEat.signal();
            } finally {
                ROOM.unlock();
            }
        }, "送外卖线程").start();

    }
}
